'use strict';
/**
 * This will create the module structure
 */
var util = require('util');
var path = require('path');
var fs   = require('fs');
var chalk = require('chalk');
var _ = require('underscore');
var ScriptBase = require('../../lib/script-base.js');
var preference = require('../../lib/preference');
var us = require('underscore.string');

var Generator = module.exports = function()
{
    ScriptBase.apply(this, arguments);
    this.config = preference.getConfig();
};

util.inherits(Generator, ScriptBase);

/**
 * writing the defintion to the package.json file
 */
Generator.prototype.__writeToPackage = function(moduleName , modulePath , callback)
{
    var packagePath = path.join( process.cwd() , 'package.json')
    var packageJson = require( packagePath );
    if (!packageJson.ngmodules) {
        packageJson.ngmodules = {};
    }
    if (!modulePath) {
        if (callback && typeof callback === 'function') {
            callback();
        }
        return;
    }
    /**
     * here is the problem with different system the path seperator is different
     * when move cross platform that this won't work, so instead we only store the
     * name part in the json file
     */
    var ps = modulePath.split(path.sep);
    // only want the last part of the path
    packageJson.ngmodules[moduleName] = ps[ps.length-1];

    var packageJsonStr = JSON.stringify(packageJson , null , 4);

    fs.writeFile(packagePath , packageJsonStr , 'utf-8' , function(error)
    {
        if (error) {
            console.log(chalk.red('Fail to write to package.json file!'));
            throw error; // terminate?
        }
        if (callback && typeof callback === 'function') {
            callback();
        }
    });
};

/**
 * final call to generate the module file
 */
Generator.prototype.createModuleFile = function()
{
	var moduleName = this.moduleName = (this.name+'').toLowerCase(); // we keep whatever the original structure just make it lowercase
    //us.camelize( this.name , true);
    var modulePathName = this.createModulePath(this.moduleName);

	this.ngRoute = this.config.ngRoute;

    var modulePath = path.join('scripts' , 'modules' , modulePathName);

	this.appTemplate(
		'module',
		path.join(modulePath , 'module')
	);

    var pathToAppModule = this.getAppPath( modulePath );

    var app_js_file = path.join('app','scripts','app.js');
    var appJsFile = fs.readFileSync(app_js_file, 'utf-8');
    // @TODO need to look at this regex to figure out how to do the module in multiple line
    var pattern = new RegExp(/(angular\.module\(')(.*)([\s\S]\]\))/gi);
    var matches = appJsFile.match(pattern);
    if (matches) {
        var pattern1 = new RegExp('\\]\\)' + '$');
        var line = matches[0].replace(pattern1 , ",'" + moduleName + "'])");
        var newFile = appJsFile.replace(pattern , line);

        fs.writeFile(app_js_file , newFile , 'utf-8' , function(error)
        {
            if (error) {
                console.log(chalk.red('Fail to write to app.js file!'));
                throw error; // terminate?
            }
        });
    }
    else {
        console.log(
            chalk.red(
                'Could not find angular app.js file. Did you modified it? Please manually add your module.'
            )
        );
    }
    // @2016-09-11 stop using this option, because it creates a cross platform and existing project compatibility issue
    // finalize
    //this.writeToPackage(moduleName , pathToAppModule , function()
    //{
        // now add the module to the app.js file

    // });
};

// -- EOF --
